import Model from './abstract';
import ModelGroup from './user/group';
import downloadFiles, { downloadFile } from '../utils/downImgUtils';

export default class ModelUser extends Model {
      
      constructor() {
            super();
            this.mainTable = 'user';
            this.pk = 'user_id';
            this.serverPk = 'server_user_id';
            this.versionName = 'version';
            this.dateAddedName = 'date_added';
            this.lastUpdatedName = 'last_updated';
            this.modelGroup = new ModelGroup();
      }

      /**
       * 通过pincode登陆用户
       */
      async login(pincode) {
            let row = await this.fetchOne("SELECT * FROM `user` WHERE `pincode` = ? LIMIT 0,1", [pincode]);
            if (row) {
                  let userId = row.user_id;
                  if (row.master_flag == 1) {
                        row.permissions = await this.getPermissions(userId);
                  }
                  return row;
            }
            return null;
      }

      /**
       * 获取员工列表
       */
      async getUsers(start = 0, limit = 0) {
            let users = await this.query(start, limit);
            for (user of users) {
                  let userId = user.user_id;
                  user.groups = await this.getGroupIds(userId);
            }
            return users;
      }

      /**
       * 获取员工资料
       */
      async getUser(userId) {
            let user = await this.get(userId);
            if (user && user.user_id) {
                  user.groups = await this.getGroupIds(userId);
            }
            return user;
      }

      /**
       * 获取员工Permissions
       */
      async getPermissions(userId) {
            let permissions = [];
            let groupIds = await this.getGroupIds(userId);
            console.log("group ids >>> ", groupIds);
            for (groupId of groupIds) {
                  let perms = await this.modelGroup.getPermission(groupId);
                  console.log("perms >>> ", perms);
                  if (perms !== null) {
                        for(perm of perms) {
                              if (!permissions.includes(perm)) {
                                    permissions.push(perm);
                              }
                        }
                  }
            }
            return permissions;
      }


      /**
       * 获取当前员工分组ID
       */
      async getGroupIds(userId) {
            let ids = [];
            let groups = await this.fetchRows("SELECT `group_id` FROM `user_to_group` WHERE `user_id` = ?", [userId]);
            for (group of groups) {
                  ids.push(group.group_id);
            }
            return ids;
      }

      /**
       * 获取当前商品分类ID
       */
      async getGroupIdByServerPk(serverPk) {
            let row = await this.fetchOne("SELECT `group_id` FROM `user_group` WHERE `server_group_id` = ? LIMIT 0,1", [serverPk]);
            if (row && row.group_id) {
                  return row.group_id;
            }
            return 0;
      }

      /**
       * 保存员工
       */
      async saveUser(data, userId = 0) {
            let groups = [];
            if (data.groups) {
                  groups = data.groups;
                  delete data.groups;
            }
            userId = parseInt(userId);
            userId = await this.save(data, userId);
            if (userId > 0) {
                  await this.saveGroupIds(userId, groups);
            }
            return userId;
      }

      /**
       * 通过serverPk保存员工
       */
      async saveUserByServerPk(data, serverUserId = 0) {
            let groups = [];
            if (data.groups) {
                  groups = data.groups;
                  delete data.groups;
            }
            console.log("groups >>> ", groups);
            let userId = await this.saveByServerPk(data, serverUserId);
            if (userId > 0) {
                  await this.saveGroupIdsByServerPks(userId, groups);
            }
            return userId;
      }

      /**
       * 保存商品分类
       */
      async saveGroupIds(userId, ids = []) {
            if (userId > 0) {
                  if (!Array.isArray(ids)) {
                        ids = [];
                  }
                  let oldIds = await this.getGroupIds(userId);
                  let newIds = ids.filter(el => !oldIds.includes(el));
                  let delIds = oldIds.filter(el => !ids.includes(el));
                  for (id of newIds) {
                        if (id > 0) {
                              let data = {
                                    user_id: userId,
                                    group_id: id
                              };
                              await this.insert("user_to_group", data);
                        }
                  }
                  for (id of delIds) {
                        let params = {
                              user_id: userId,
                              group_id: id
                        };
                        await this.delete("user_to_group", params);
                  }
            }
      }

      /**
       * 保存商品分类
       */
      async saveGroupIdsByServerPks(userId, serverIds = []) {
            let ids = [];
            if (!Array.isArray(serverIds)) {
                  serverIds = [];
            }
            for (serverId of serverIds) {
                  let id = await this.getGroupIdByServerPk(serverId);
                  ids.push(id);
            }
            //console.log(ids);
            await this.saveGroupIds(userId, ids);
      }

      /**
       * 保存图片
       */
      async saveLogo(userId, logo) {
            let data = {
                  logo: logo
            };
            return await this.update(this.mainTable, data, {user_id: userId});
      }

      /**
       * 删除商品资料
       */
      async removeUser(userId) {
            let user = await this.get(userId);
            if (user) {
                  // 删除图片
                  if (user.logo) {
                  }
                  // 删除用户与会员组对照表
                  await this.delete("user_to_group", {user_id: userId});
                  await this.remove(userId);
            }
      }

      /**
       * 删除商品分类
       */
      async removeUserByServerPk(serverPk) {
            let userId = await this.getIdByServerPk(serverPk);
            if (userId > 0) {
                  return await this.removeUser(userId);
            }
            return false;
      }

      /**
       * 数据导入
       */
      async download(rows = []) {
            if (!Array.isArray(rows)) {
                  rows = [];
            }
            let localServerPks = await this.getServerPks();
            let remoteServerPks = [];
            for (row of rows) {
                  let serverUserId = row.server_user_id;
                  if (serverUserId > 0) {
                        remoteServerPks.push(serverUserId);
                        let version = await this.getVersionByServerPk(serverUserId);
                        if (version < row.version) {
                              let logo = null;
                              if (row.logo) {
                                    logo = row.logo;
                                    delete row.logo;
                              }
                              console.log("user row >>> ", row);
                              let userId = await this.saveUserByServerPk(row, serverUserId);
                              if (userId > 0 && logo) {
                                    let name = sprintf("user/%d", userId);
                                    let file = await downloadFile(logo, name);
                                    if (file !== null) {
                                          console.log("user image file >>>> ", file);
                                          await this.saveLogo(userId, file);
                                    }
                              }
                        }
                  }
            }

            let delServerPks = localServerPks.filter(el => !remoteServerPks.includes(el));
            for (serverPk of delServerPks) {
                  if (serverPk > 0) {
                        await this.removeUserByServerPk(serverPk);
                  }
            }
            return true;
      }

      /**
       * 数据上传
       */
      async upload() {
            return true;            
      }

}